﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using SpiderContract;
using Common;
using ServiceStack.Redis.Support;
using MySql.Data.MySqlClient;
using System.Threading;
using System.Data;
using System.Web.Security;

namespace SpiderServer.Service
{
	public class SpiderService : ISpiderService
	{
		#region ISpiderService 成员

		public void StartJob(int jobId)
		{
			JobManager.Start(jobId);
			Global.DBAccess.ExecuteNonQuery("update crawl_job set status= 1 where job_id=@job_id", new MySqlParameter("job_id", jobId));
			Configs.UpdateJob(jobId);
		}

		public void UpdateJob(int jobId)
		{
			Configs.UpdateJob(jobId);
		}

		public void UpdateJobFile(int fileId)
		{
			Configs.UpdateJobFile(fileId);
		}

		public void ReCrawl(int jobId, string[] urls)
		{
			LinkInfo link = null;
			var ser = new ObjectSerializer();
			CrawlJobInfo jobInfo = Configs.GetCrawlJobById(jobId);
			Job job = new Job(jobId);
			using (var redisClent = Global.GetRedisClient())
			{
				foreach (string url in urls)
				{
					link = new LinkInfo();
					link.Url = url;
					link.JobId = jobId;
					Global.DBAccess.ExecuteNonQuery("delete from crawl_data_page where hash=@hash", new MySqlParameter("hash", url.GetHashCode()));
				}

				foreach (string url in urls)
				{
					link = new LinkInfo();
					link.Url = url;
					link.JobId = jobId;
					job.ReCrawl(url);
				}
			}
		}

		public bool VerifyUser(string email, string pwd, out CrawlJobInfo[] jobs)
		{
			jobs = null;
			pwd = FormsAuthentication.HashPasswordForStoringInConfigFile(string.Format("abc{0}abc", pwd), "MD5");
			object objUserId = Global.DBAccess.ExecuteScalar("select uid from user_info where email=@email and pwd=@pwd", 
				new MySqlParameter("email", email),
				new MySqlParameter("pwd", pwd)
			);

			if (objUserId != null && objUserId != DBNull.Value)
			{
				int uid = Convert.ToInt32(objUserId);
				DataTable dt = Global.DBAccess.GetTable("select job_id from crawl_job where uid=@uid",
					new MySqlParameter[]
					{
						new MySqlParameter("uid", uid)
					}
				);

				if (dt.Rows.Count > 0)
				{
					int i = 0;
					jobs = new CrawlJobInfo[dt.Rows.Count];
					foreach (DataRow dr in dt.Rows)
					{
						jobs[i] = Configs.GetCrawlJobById(Convert.ToInt32(dr["job_id"]));
						i++;
					}
				}
				return true;
			}
			return false;
		}

		public LinkInfo PopLinkFromWaitQueue(int jobId)
		{
			Job job = JobManager.GetJob(jobId);
			if (job != null)
			{
				return job.PopLinkFromWaitQueue();
			}
			return null;
		}

		public void PushPageData(PageDataInfo data)
		{
			Job job = JobManager.GetJob(data.JobId);
			if (job != null)
			{
				job.PushPageData(data);
			}
		}

		#endregion
	}
}
